package edu.whu.demo.service;

import edu.whu.demo.dao.UserRepository;
import edu.whu.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {
    @Autowired
    UserRepository userRepository;

    /**
     * 将查询结果添加到缓存user中，以name作为key
     * @param name
     * @return
     */
    @Cacheable(cacheNames = "user",key = "#name",condition = "#name!=null")
    public User getUser(String name){
        Optional<User> u = userRepository.findById(name);
        return u.isEmpty()?null:u.get();
    }

    /**
     * 移除缓存user中key为userName的对象
     * @param userName
     */
    @CacheEvict(cacheNames = "user",key = "#userName")
    public void deleteUser(String userName) {
        userRepository.deleteById(userName);
    }

    /**
     * 移除缓存user中key为name的对象
     * @param name
     * @param user
     * @return
     */
    @CacheEvict(cacheNames = "user",key = "#name")
    public User updateUser(String name, User user) {
        if(name==null ||!name.equals(user.getName())||userRepository.findById(name).isEmpty()){
            throw new RuntimeException("update error");
        }
        return userRepository.saveAndFlush(user);
    }


    public List<User> findAll(){
        return userRepository.findAll();
    }

    public User addUser(User user){
        return userRepository.save(user);
    }


}
